package ru.isys.xml.util.builder;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import javax.xml.transform.TransformerException;

import org.dom4j.DocumentException;

import ru.isys.xml.XmlItem;
import ru.isys.xml.template.Bind;
import ru.isys.xml.template.BindEntyty;
import ru.isys.xml.template.DivInput;
import ru.isys.xml.template.FormInputFormOutput;
import ru.isys.xml.template.IncludeRequest;
import ru.isys.xml.template.Model;
import ru.isys.xml.template.Request;
import ru.isys.xml.template.Response;

public class OutXmlBuilder
{
    String tmpfile = "request.xml";
    Request request;
    Response response;
    List <XmlItem> xmlItems;    
    BindBuilder bindBuilder;
    FormBuilder formBuilder;
    String xml;
    
    public OutXmlBuilder(List<XmlItem> xmlItems)
    {

        this.xmlItems= xmlItems;      
        this.request = new Request(false);
        this.response = new Response(false);     
        this.bindBuilder=new BindBuilder(this.xmlItems);
        this.formBuilder=new FormBuilder(this.xmlItems);
        this.xml="";
    }
    
    public String build(String modelXml) throws TransformerException, IOException, DocumentException{
                
       
        xml+=IncludeRequest.tag;
        xml+=request.getTag();
        xml+=Model.TAG;        
        xml+=modelXml;
        xml+=Model.CLOSE_TAG;
        xml+=bindBuilder.build();
        xml+=formBuilder.build();
        
        xml+=Request.CLOSE_TAG;
        return transformAndShow(xml);       
    }
    
    public String transformAndShow(String xml) throws TransformerException, IOException, DocumentException
    {
        StringWriter sw = new StringWriter();
        PrintWriter fw = new PrintWriter(new FileWriter(this.tmpfile));        
        System.out.println(xml);
        fw.print(xml);
        fw.flush();
        return xml;
    }
    
    
    
}
